import React from 'react'

import { Form, Input, Button } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import './index.css'
import axios from 'axios'


import JSEncrypt from 'jsencrypt'


// 登录组件
export default function Login (props) {

  //如果需要在里面依赖公共状态更新组件，需要将状态解构出来
  //let {a} = props

  // useEffect(() => {
  //   console.log(props)
  // })

  // 编程式跳转
  const navigate = useNavigate()

  // 登录校验的方法，与后端联系
  const onFinish = (value) => {
    // 先获取公钥
    axios({
      method: 'post',
      url: 'http://localhost:8081/user/getPublicKey',
      data: {
        username: value.username
      }
    }).then(function (res) {
      if (res.data.code !== 200) {
        alert("用户验证失败")
      } else {
        let encryptor = new JSEncrypt() // 新建JSEncrypt对象
        let cipherTextValue = ''
        encryptor.setPublicKey(res.data.data)
        cipherTextValue = encryptor.encrypt(value.password)
        axios({
          method: 'post',
          url: 'http://localhost:8081/user/doLogin',
          data: {
            username: value.username,
            cipherText: cipherTextValue
          }
        }).then(function (resp) {
          if (resp.data.code !== 200) {
            alert('用户登陆失败')
          } else {
            // 将token存入本地
            localStorage.setItem('satoken', resp.data.data.tokenValue)
            localStorage.setItem('username', resp.data.data.username)
            //跳转至首页
            navigate('/index')
          }
        })
      }
    })
  }
  return (

    <div className='background'>
      <div id='components-form-demo-normal-login' className='formContainer'>
        <div className='loginTitle'>数据填报</div>
        <Form
          name="normal_login"
          className="login-form"
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: 'Please input your Username!',
              },
            ]}
          >
            <Input className='inputBox'
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your Password!',
              },
            ]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>


          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              Log in
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

